<html>
<head>
	<title>Events test</title>
	<script type="text/javascript" src="static/jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="static/JSON.js"></script>
	<script type="text/javascript">
		function EventsBridge(trigger_server_events_url, get_client_events_url){
			var self = this;
			
			self.server_trigger = function(event_kind, event_data){
				event_data = event_data || {};
				$.ajax({type:'POST',
						url:trigger_server_events_url,
						data:{"event_kind": event_kind, "event_data": JSON.encode(event_data)}});
			}
			self.handlers = {};
			self.client_bind = function(event_kind, handler){
				if(!self.handlers[event_kind]){
					self.handlers[event_kind] = [];
				}
				self.handlers[event_kind].push(handler);
			}
			
			function get_client_events(){
				function trigger_client_events(events){
					$.each(events, function(i,e){
						if(self.handlers[e.event_kind]){
							$.each(self.handlers[e.event_kind], function(j,h){ h(e); });
						}
					});
					get_client_events();
				}
				$.ajax({type:'GET', url:get_client_events_url,
						dataType:'json', success: trigger_client_events });
			}
			get_client_events();
		}

		
		$(function(){
			var events_bridge = new EventsBridge('{% url trigger_server_event %}', '{% url get_client_events %}');
			events_bridge.client_bind("SHOW_ZOMBIE", function(e){
				var $img = $('<img src="/static/zombie.png"></img>')
					.click(function(){
						$(this).fadeOut();
						events_bridge.server_trigger("ZOMBIE_KILLED");
					})
					.css('top', e.event_data.y)
					.css('left', e.event_data.x);
				$('body').append($img); 
			});
			events_bridge.client_bind("UPDATE_SCORE", function(e){
				$('span.score').html(e.event_data);
			});
		});
	</script>
	<style type="text/css">
		body {
			margin: 0;
			padding: 0;
			cursor: crosshair;
			height: 100%;
		}
		img {
			position: absolute;
		}
	</style>
</head>
<body>
Zombies aniquilados: <span class="score"></span>
</body>
</html>